<template>
  <page-container title="更换头像">
    <div class="avatar-upload-container">
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        class="avatar-uploader"
        :show-file-list="false"
        :on-change="onSelectFile"
        accept=".jpg,.jpeg,.png,.gif"
      >
        <template #trigger>
          <div class="avatar-preview">
            <img v-if="imgUrl" :src="imgUrl" class="avatar" alt="用户头像" />
            <div v-else class="avatar-uploader-icon">
              <el-icon class="upload-icon"><Plus /></el-icon>
              <span class="upload-text">点击上传头像</span>
              <span class="upload-hint">支持 JPG/PNG/GIF 格式，小于2MB</span>
            </div>
          </div>
        </template>
      </el-upload>

      <div class="action-buttons">
        <el-button
          @click="uploadRef?.$el.querySelector('input')?.click()"
          type="primary"
          :icon="Plus"
          size="large"
        >
          选择图片
        </el-button>
        <el-button
          @click="onUpdateAvatar"
          type="success"
          :icon="Upload"
          size="large"
          :disabled="!imgUrl || isLoading"
          :loading="isLoading"
        >
          {{ isLoading ? '上传中...' : '上传头像' }}
        </el-button>
      </div>
    </div>
  </page-container>
</template>

<script setup>
import { ref } from 'vue'
import { Plus, Upload } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userUpdateAvatarService, getUserInfo } from '@/api/user'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const imgUrl = ref(userStore.user?.user_pic || '')
const uploadRef = ref()
const isLoading = ref(false)
const router = useRouter()
const showProfileSubMenu = ref(false)

// 允许的文件类型
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/gif']
const MAX_FILE_SIZE = 2 * 1024 * 1024 // 2MB

// 文件选择处理
const onSelectFile = (uploadFile) => {
  const file = uploadFile.raw

  // 验证文件类型
  if (!ALLOWED_TYPES.includes(file.type)) {
    ElMessage.error('只支持 JPG/PNG/GIF 格式的图片')
    return false
  }

  // 验证文件大小
  if (file.size > MAX_FILE_SIZE) {
    ElMessage.error('图片大小不能超过2MB')
    return false
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    imgUrl.value = e.target.result
  }
  reader.onerror = () => {
    ElMessage.error('图片读取失败，请重试')
  }
  reader.readAsDataURL(file)

  return true
}

// 上传头像
const onUpdateAvatar = async () => {
  if (!imgUrl.value) {
    ElMessage.warning('请先选择图片')
    return
  }

  isLoading.value = true

  try {
    // 1. 获取图片Blob
    const response = await fetch(imgUrl.value)
    const blob = await response.blob()

    // 2. 创建FormData
    const formData = new FormData()
    formData.append('file', blob, `file.${blob.type.split('/')[1]}`) // 自动获取扩展名

    // 3. 调用上传接口
    await userUpdateAvatarService(formData)

    // 4. 更新用户信息
    const updatedUser = await getUserInfo(userStore.user.id); // 调用 API 获取最新数据

    userStore.setUser(updatedUser.data.data);
    console.log(useUserStore().role);

    ElMessage.success('头像更新成功')

    setTimeout(() => {
      // 保持子菜单展开状态
      showProfileSubMenu.value = true
      const role = useUserStore().role
      router.push(`/${role}/profile`); // 动态生成路径
    }, 1000)
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error(`头像更新失败: ${error.message || '服务器错误'}`)
  } finally {
    isLoading.value = false
  }
}
</script>

<style lang="scss" scoped>
.avatar-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
  padding: 20px;
}

.avatar-uploader {
  width: 100%;
  max-width: 300px;

  :deep() {
    .avatar-preview {
      position: relative;
      width: 100%;
      aspect-ratio: 1/1;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: #f5f7fa;
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
        border-color: var(--el-color-primary);
      }
    }

    .avatar {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .el-upload {
      width: 100%;
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      transition: var(--el-transition-duration-fast);
    }
  }
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 8px;
  padding: 20px;
  color: var(--el-text-color-secondary);
  text-align: center;

  .upload-icon {
    font-size: 32px;
    margin-bottom: 8px;
  }

  .upload-text {
    font-size: 16px;
    font-weight: 500;
  }

  .upload-hint {
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
}

.action-buttons {
  display: flex;
  gap: 16px;
  justify-content: center;
  width: 100%;
  flex-wrap: wrap;
}

@media (max-width: 480px) {
  .action-buttons {
    flex-direction: column;
    align-items: center;

    .el-button {
      width: 100%;
      max-width: 300px;
    }
  }
}
</style>
